﻿using nplJobsBLL.ProcessJob;
using nplJobsBLL.ProcessJobSeeker;
using nplJobsCommon.JobSeeker;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

public partial class JobSeeker_AppliedJobs : System.Web.UI.Page
{
    #region Variables and Properties
    public Int64 AppliedJobID { get; set; }
    Image sortImage = new Image();
    Image sortSecondImage = new Image();
    Image sortThirdImage = new Image();

    public int CurrentSortDirection
    {
        get
        {
            if (Session["SortDireaction"] == null)
                return 0;
            else
                return int.Parse(Session["SortDireaction"].ToString());
        }
        set
        {
            Session["SortDireaction"] = value;
        }
    }
    #endregion

    #region PopulatePager
    /// <summary>
    /// Populate pager to paging in the griv view
    /// </summary>
    /// <param name="recordCount"></param>
    /// <param name="currentPage"></param>
    private void PopulatePager(int recordCount, int currentPage)
    {
        double dblPageCount = (double)((decimal)recordCount / decimal.Parse(ddlPageSize.SelectedValue));
        int pageCount = (int)Math.Ceiling(dblPageCount);
        List<ListItem> pages = new List<ListItem>();
        if (pageCount > 0)
        {
            pages.Add(new ListItem("First", "1", currentPage > 1));
            for (int i = 1; i <= pageCount; i++)
            {
                pages.Add(new ListItem(i.ToString(), i.ToString(), i != currentPage));
            }
            if (pageCount == 1)
                pages.Add(new ListItem("Last", pageCount.ToString(), false));
            else
                pages.Add(new ListItem("Last", pageCount.ToString(), currentPage < pageCount));
        }
        rptPager.DataSource = pages;
        rptPager.DataBind();
    }
    #endregion

    #region GetCustomersPageWise
    /// <summary>
    /// Get customers page wise
    /// </summary>
    /// <param name="pageIndex"></param>
    private void GetCustomersPageWise(int pageIndex)
    {
        MembershipUser userInfo = System.Web.Security.Membership.GetUser(HttpContext.Current.User.Identity.Name);
        System.Web.Security.MembershipUser currentUser = System.Web.Security.Membership.GetUser();
        Guid jobseekerID = (Guid)userInfo.ProviderUserKey;

        ProcessAppliedJobsPageWise appliedJobs = new ProcessAppliedJobsPageWise();
        appliedJobs.PageIndex = pageIndex == -1 ? 1 : pageIndex;

        //appliedJobs.PageSize = int.Parse(ddlPageSize.SelectedValue);
        if (pageIndex == -1)
        {
            int maxValue = ddlPageSize.Items.Cast<ListItem>().Select(item => int.Parse(item.Value)).Max();
            appliedJobs.PageSize = maxValue;
            ddlPageSize.SelectedIndex = ddlPageSize.Items.IndexOf(ddlPageSize.Items.FindByText(maxValue.ToString()));
        }
        else
        {
            appliedJobs.PageSize = int.Parse(ddlPageSize.SelectedValue);
        }
        appliedJobs.JobseekerID = jobseekerID;
        appliedJobs.invoke();
        List<AppliedJobToDisplay> appliedJobPageWise = appliedJobs.AppliedJobToDisplay;
        Session["AppliedJobs"] = appliedJobPageWise;
        BindJobList(appliedJobPageWise);


        int recordCount = appliedJobs.RecordCount;
        this.PopulatePager(recordCount, pageIndex);
    }
    #endregion

    #region BindJobList
    /// <summary>
    /// Bind job list to the griv view
    /// </summary>
    /// <param name="appliedJobs"></param>
    private void BindJobList(List<AppliedJobToDisplay> appliedJobs)
    {
        gvJobList.DataSource = appliedJobs;
        gvJobList.DataBind();
        sortImage.ImageUrl = "../Images/view_sort_ascending.png";
        //sortSecondImage.ImageUrl = "../Images/view_sort_ascending.png";
        //sortThirdImage.ImageUrl = "../Images/view_sort_ascending.png";

        if (appliedJobs.Count > 0)
            gvJobList.HeaderRow.Cells[1].Controls.Add(sortImage);
        //gvJobList.HeaderRow.Cells[3].Controls.Add(sortSecondImage);
        //gvJobList.HeaderRow.Cells[4].Controls.Add(sortThirdImage);

        if (appliedJobs.Count == 0)
        {
            rptPager.Visible = false;
            ddlPageSize.Visible = false;
        }
        else
        {
            ddlPageSize.Visible = true;
            rptPager.Visible = true;
        }
    }
    #endregion

    #region LoadAppliedJobToDisplay
    /// <summary>
    /// Load applied job to show in the grid view
    /// </summary>
    /// <returns></returns>
    private List<AppliedJobToDisplay> LoadAppliedJobToDisplay()
    {
        ProcessAppliedJobToDisplay appliedJobToDisplay = new ProcessAppliedJobToDisplay();
        MembershipUser userInfo = System.Web.Security.Membership.GetUser(HttpContext.Current.User.Identity.Name);
        System.Web.Security.MembershipUser currentUser = System.Web.Security.Membership.GetUser();
        if (userInfo != null)
        {
            Guid jobseekerID = (Guid)userInfo.ProviderUserKey;
            appliedJobToDisplay.JobseekerID = jobseekerID;
            appliedJobToDisplay.AppliedJobID = this.AppliedJobID;
            appliedJobToDisplay.invoke();
        }

        return appliedJobToDisplay.AppliedJobToDisplay;
    }
    #endregion

    #region LoadAppliedJobs
    /// <summary>
    /// Load applied jobs
    /// </summary>
    private void LoadAppliedJobs()
    {
        List<AppliedJobToDisplay> appliedJobs = new List<AppliedJobToDisplay>();
        this.AppliedJobID = -1;
        appliedJobs = LoadAppliedJobToDisplay();
        if (appliedJobs != null)
        {
            Session["AppliedJobs"] = appliedJobs;
            //BindJobList(appliedJobs);
            //int numberPerPage = ConfigurationManager.AppSettings["PagingNumberPerPage"] != null ? int.Parse(ConfigurationManager.AppSettings["PagingNumberPerPage"].ToString()) : 0;
            this.GetCustomersPageWise(1);
        }
    }
    #endregion

    #region RefreshAppliedJobs
    /// <summary>
    /// Refresh applied jobs
    /// </summary>
    private void RefreshAppliedJobs(int value)
    {
        List<AppliedJobToDisplay> appliedJobs = new List<AppliedJobToDisplay>();
        this.AppliedJobID = -1;
        appliedJobs = LoadAppliedJobToDisplay();
        if (appliedJobs != null)
        {
            Session["AppliedJobs"] = appliedJobs;
            //BindJobList(appliedJobs);
            //  int numberPerPage = ConfigurationManager.AppSettings["PagingNumberPerPage"] != null ? int.Parse(ConfigurationManager.AppSettings["PagingNumberPerPage"].ToString()) : 0;
            this.GetCustomersPageWise(value);
        }
        else
        {
            BindJobList(appliedJobs);
        }
    }
    #endregion

    #region Events
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Context.User.Identity.IsAuthenticated)
            Response.Redirect("~/Default.aspx");

        if (!IsPostBack)
        {
            Page.Title = "npljobs.com || Applied jobs";

            Label lblTitle = Page.Master.FindControl("lblTitle") != null ? (Label)Page.Master.FindControl("lblTitle") : new Label();
            lblTitle.Text = "Applied job(s)";

            //txtSearch.Attributes.Add("onblur", "WaterMark(this, event);");
            //txtSearch.Attributes.Add("onfocus", "WaterMark(this, event);");

            LoadAppliedJobs();


        }

    }
    protected void Page_Changed(object sender, EventArgs e)
    {
        int pageIndex = int.Parse((sender as LinkButton).CommandArgument);
        this.GetCustomersPageWise(pageIndex);
    }
    protected void ddlPageSize_Changed(object sender, EventArgs e)
    {
        //int numberPerPage = ConfigurationManager.AppSettings["PagingNumberPerPage"] != null ? int.Parse(ConfigurationManager.AppSettings["PagingNumberPerPage"].ToString()) : 0;
        this.GetCustomersPageWise(1);
    }
    protected void gvJobList_Sorting(object sender, GridViewSortEventArgs e)
    {
        List<AppliedJobToDisplay> appliedJobs = (List<AppliedJobToDisplay>)Session["AppliedJobs"];
        int currentSortDirection = CurrentSortDirection;
        if (appliedJobs != null)
        {
            //int numberPerPage = ConfigurationManager.AppSettings["PagingNumberPerPage"] != null ? int.Parse(ConfigurationManager.AppSettings["PagingNumberPerPage"].ToString()) : 0;
            this.GetCustomersPageWise(1);

            var param = Expression.Parameter(typeof(AppliedJobToDisplay), e.SortExpression);
            var sortExpression = Expression.Lambda<Func<AppliedJobToDisplay, object>>(Expression.Convert(Expression.Property(param, e.SortExpression), typeof(object)), param);

            //Set the list ordered ascending as datasource
            if (currentSortDirection == (int)SortDirection.Ascending)
            {
                gvJobList.DataSource = appliedJobs.AsQueryable<AppliedJobToDisplay>().OrderBy(sortExpression).ToList();
            }
            //Set the list ordered descending as datasource
            else
            {
                gvJobList.DataSource = appliedJobs.AsQueryable<AppliedJobToDisplay>().OrderByDescending(sortExpression).ToList();
            }
            if (currentSortDirection == (int)SortDirection.Ascending)
            {
                CurrentSortDirection = (int)SortDirection.Descending;
                sortImage.ImageUrl = "../Images/view_sort_ascending.png";
                //sortSecondImage.ImageUrl = "../Images/view_sort_ascending.png";
                //sortThirdImage.ImageUrl = "../Images/view_sort_ascending.png";
            }
            else
            {
                CurrentSortDirection = (int)SortDirection.Ascending;
                sortImage.ImageUrl = "../Images/view_sort_descending.png";
                //sortSecondImage.ImageUrl = "../Images/view_sort_descending.png";
                //sortThirdImage.ImageUrl = "../Images/view_sort_descending.png";
            }

            gvJobList.DataBind();
            int columnIndex = 0;
            foreach (DataControlFieldHeaderCell headerCell in gvJobList.HeaderRow.Cells)
            {
                if (headerCell.ContainingField.SortExpression == e.SortExpression)
                {
                    columnIndex = gvJobList.HeaderRow.Cells.GetCellIndex(headerCell);
                }
            }

            gvJobList.HeaderRow.Cells[1].Controls.Add(sortImage);
            //gvJobList.HeaderRow.Cells[3].Controls.Add(sortSecondImage);
            //gvJobList.HeaderRow.Cells[4].Controls.Add(sortThirdImage);
        }
    }
    protected void gvJobList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            int applicationDateline = ((AppliedJobToDisplay)e.Row.DataItem).ApplicationDateline;
            if (applicationDateline <= 0)
            {
                Label lblApplicationDateline = (Label)e.Row.FindControl("lblApplicationDateline");
                lblApplicationDateline.ForeColor = System.Drawing.Color.Red;
                lblApplicationDateline.Text = "Expired";
                //e.Row.Cells[4].Text = "Expired";
            }
            else
            {
                Label lblApplicationDateline = (Label)e.Row.FindControl("lblApplicationDateline");
                lblApplicationDateline.Text = applicationDateline.ToString() + " days";
                // int dl = ((AppliedJobToDisplay)e.Row.DataItem).ApplicationDateline;
                // e.Row.Cells[4].Text = dl.ToString() + " days";
            }
        }
    }
    protected void txtSearch_TextChanged(object sender, EventArgs e)
    {
        if (txtSearch.Text == "Write text and press enter")
            return;
        else
        {
            if (txtSearch.Text != string.Empty)
            {
                MembershipUser userInfo = System.Web.Security.Membership.GetUser(HttpContext.Current.User.Identity.Name);
                System.Web.Security.MembershipUser currentUser = System.Web.Security.Membership.GetUser();
                Guid jobSeekerID = (Guid)userInfo.ProviderUserKey;

                int dealine = -1;
                bool isParsed = int.TryParse(txtSearch.Text.Trim(), out dealine);

                ProcessSelectAppliedJobByParam selectAppliedJob = new ProcessSelectAppliedJobByParam();
                selectAppliedJob.JobTitle = ddlSearchBy.SelectedItem.Text.Equals("Job Title") ? txtSearch.Text.Trim() : string.Empty;
                selectAppliedJob.Location = ddlSearchBy.SelectedItem.Text.Equals("Location") ? txtSearch.Text.Trim() : string.Empty;
                selectAppliedJob.Deadline = ddlSearchBy.SelectedItem.Text.Equals("Deadline") ? dealine : 0;

                selectAppliedJob.JobSeekerId = jobSeekerID;
                List<AppliedJobToDisplay> appliedJobs = new List<AppliedJobToDisplay>();

                if (ddlSearchBy.SelectedItem.Text.Equals("Deadline") && selectAppliedJob.Deadline <= 0)
                {
                    appliedJobs = new List<AppliedJobToDisplay>();
                }
                else
                {
                    selectAppliedJob.invoke();
                }

                if (selectAppliedJob.AppliedJobToDisplay != null && selectAppliedJob.AppliedJobToDisplay.Count > 0)
                {
                    appliedJobs = selectAppliedJob.AppliedJobToDisplay;
                    BindJobList(appliedJobs);
                }
                else
                {
                    BindJobList(appliedJobs);
                }
            }
        }

        if (ddlSearchBy.Text == "Deadline")
        {
            lblMessage.InnerText = "i.e. 10 (in days)";
        }
        else
        {
            lblMessage.InnerText = "";
        }
    }
    protected void btnYes_Click(object sender, ImageClickEventArgs e)
    {
        lblSaveMsg.Text = string.Empty;

        DataTable dtAppliedJobIds = new DataTable();
        dtAppliedJobIds.Columns.Add("AppliedJobID", typeof(int));
        dtAppliedJobIds.NewRow();

        List<string> ids = new List<string>();
        string id = string.Empty;

        for (int i = 0; i < gvJobList.Rows.Count; i++)
        {
            CheckBox cb = (CheckBox)gvJobList.Rows[i].Cells[4].FindControl("chkDelete");
            if (cb != null)
            {
                if (cb.Checked)
                {
                    id = gvJobList.Rows[i].Cells[0].Text;
                    dtAppliedJobIds.Rows.Add(id);
                }
            }
        }

        bool isDeleted = false;

        ProcessDeleteJobSeekerAppliedJobs deleteAppliedJobs = new ProcessDeleteJobSeekerAppliedJobs();
        deleteAppliedJobs.AppliedJobToDisplay = dtAppliedJobIds;
        deleteAppliedJobs.invoke();
        isDeleted = deleteAppliedJobs.IsDeleted;

        if (isDeleted)
        {
            lblSaveMsg.Text = "Selected jobs are deleted";
            LoadAppliedJobs();
            lblSaveMsg.ForeColor = System.Drawing.Color.Green;
            ScriptManager.RegisterStartupScript(this, GetType(), "ClearSaveMsg", "ClearSaveMsg();", true);

        }
        else
        {
            lblSaveMsg.ForeColor = System.Drawing.Color.Red;
            lblSaveMsg.Text = "Failed to delete selected jobs";
            ScriptManager.RegisterStartupScript(this, GetType(), "ClearSaveMsg", "ClearSaveMsg();", true);
        }
    }
    public void btnDeleteSeledRows_Click(object sender, EventArgs e)
    {
        lblSaveMsg.Text = string.Empty;
        lblText.InnerText = "Are you sure to delete job(s)?";
        ModalPopupExtender1.Show();
    }

    //protected void ddlSearchBy_SelectedIndexChanged(object sender, EventArgs e)
    //{
    //   // if (ddlSearchBy.Text == "All")
    //   // {
    //   //     RefreshAppliedJobs();
    //   // }
    //   // else
    //    if (ddlSearchBy.Text == "Deadline")
    //    {
    //      //  RefreshAppliedJobs();
    //        lblMsg.InnerText = "i.e. Specified number is less than or equal to the dealine";
    //    }
    //    else
    //    {
    //       // RefreshAppliedJobs();
    //        lblMsg.InnerText = "";
    //    }
    //}
    #endregion
    protected void btnShowAll_Click(object sender, EventArgs e)
    {
        lblSaveMsg.Text = string.Empty;
        RefreshAppliedJobs(-1);
    }
}